package henu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import henu.IF.MakePaperIF;
import henu.IF.ManagementQuestionIF;
import henu.bean.ChoiceQuestion;
import henu.bean.JudgeQuestion;
import henu.bean.MultiChoiceQuestion;
import henu.bean.Paper;
import henu.factory.DaoFactory;

/**
 * Servlet implementation class MakePaper
 */
@WebServlet("/MakePaper")
public class MakePaper extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MakePaper() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		myway(request, response);
	}

	private void myway(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String method = request.getParameter("method");
		switch(method){
		      case "makePaper"   : makePaper(request, response);    break; 
		      case "makePaperByOwn"   : makePaperByOwn(request, response);    break;
		      case "getChoiceQuestionPages"     : getChoiceQuestionPages(request, response);      break;
		      case "getMultiChoiceQuestionPages"     : getMultiChoiceQuestionPages(request, response);      break;
		      case "getJudgeQuestionPages"     : getJudgeQuestionPages(request, response);      break;
		}
		
	}

	private void makePaper(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String tid = (String)request.getSession().getAttribute("tid");
		int classid = Integer.parseInt(request.getParameter("classPaper"));
		String starttime = request.getParameter("starttime");
		String endtime = request.getParameter("endtime");
		String papername = request.getParameter("papername");
		int subjectid = Integer.parseInt(request.getParameter("subjectid"));
		Paper p = new Paper();
		p.setTid(tid);
		p.setClassid(classid);
		p.setStarttime(starttime);
		p.setEndtime(endtime);
		p.setSubjectid(subjectid);
		p.setPapername(papername);
		MakePaperIF mp = DaoFactory.getMakePaperDaoInstance();
		boolean result = mp.makePaper(p);
		PrintWriter   out   =   response.getWriter(); 
		if(result)
            out.println("<script>alert('发布成功!');</script>"); 
		else
			out.println("<script>alert('发布失败，可能该学科题库不足!');</script>"); 
		out.println("<script>window.location.href='/MyexamOnline/teacher/makePaper.jsp'</script>");
	}

	// 手动做卷
	private void makePaperByOwn(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String tid = (String)request.getSession().getAttribute("tid");
		int subjectId = Integer.parseInt(request.getParameter("subjectId"));
		int classId = Integer.parseInt(request.getParameter("classId"));
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		String paperName = request.getParameter("paperName");
		String oneSelectedQuestions  = request.getParameter("oneSelectedQuestions");
		String twoSelectedQuestions  = request.getParameter("twoSelectedQuestions");
		String threeSelectedQuestions  = request.getParameter("threeSelectedQuestions");

		JsonReader oneReader = Json.createReader(new StringReader(oneSelectedQuestions));
		JsonReader twoReader = Json.createReader(new StringReader(twoSelectedQuestions));
		JsonReader threeReader = Json.createReader(new StringReader(threeSelectedQuestions));
		JsonArray oneJsonArray = oneReader.readArray();
		JsonArray twoJsonArray = twoReader.readArray();
		JsonArray threeJsonArray = threeReader.readArray();
		int[] oneList = new int[oneJsonArray.size()];
		int[] twoList = new int[twoJsonArray.size()];
		int[] threeList = new int[threeJsonArray.size()];
		for (int i = 0; i < oneJsonArray.size(); i++) {
		    JsonValue jsonValue = oneJsonArray.get(i);
		    String stringValue = jsonValue.toString();
		    int value = Integer.parseInt(stringValue);
		    oneList[i] = value;
		}
		for (int i = 0; i < twoJsonArray.size(); i++) {
		    JsonValue jsonValue = twoJsonArray.get(i);
		    String stringValue = jsonValue.toString();
		    int value = Integer.parseInt(stringValue);
		    twoList[i] = value;
		}
		for (int i = 0; i < threeJsonArray.size(); i++) {
		    JsonValue jsonValue = threeJsonArray.get(i);
		    String stringValue = jsonValue.toString();
		    int value = Integer.parseInt(stringValue);
		    threeList[i] = value;
		}
 
		Paper p = new Paper();
		p.setTid(tid);
		p.setClassid(classId);
		p.setStarttime(startTime);
		p.setEndtime(endTime);
		p.setSubjectid(subjectId);
		p.setPapername(paperName);
		MakePaperIF mp = DaoFactory.getMakePaperDaoInstance();
		boolean result = mp.makePaperFromList(p,oneList,twoList,threeList);
        PrintWriter out = response.getWriter();
        // 构造 JSON 响应
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

	    JsonObjectBuilder builder = Json.createObjectBuilder();
		if(result){
		    builder.add("code", 200);
		    builder.add("msg", "发布成功");
		    JsonObject data = builder.build();
	        out.print(data.toString());
		} else{
		    builder.add("code", 400);
		    builder.add("msg", "发布失败");
		    JsonObject data = builder.build();
	        out.print(data.toString());
		}
	        
	}

	// 获取选择题分页信息
	private void getChoiceQuestionPages(HttpServletRequest request, HttpServletResponse response) throws IOException {
	    // 设置响应内容类型为 JSON
	    response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");

	    // 获取传入学科id
	    String subjectid = request.getParameter("subjectid");
		
	    // pageSize: 每页展示条数
	    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		// curPage: 当前页数
	    int curPage = Integer.parseInt(request.getParameter("curPage"));
	    ManagementQuestionIF tc = DaoFactory.getTeacherDaoInstance();
	    // 选择
	    List<ChoiceQuestion> choiceQuestionList = tc.findchoiceQuestion(subjectid);
	    
	    // 总数据条目数
	    int totalItems = choiceQuestionList.size(); 
	    // 总页数
	    int totalPages = (int) Math.ceil((double) totalItems / pageSize); 
	    // 计算起始索引
	    int startNum = (curPage - 1) * pageSize;
	    // 计算结束索引
	    int endNum = Math.min(startNum + pageSize , totalItems); 
	    // 获取当前页的数据
	    choiceQuestionList = choiceQuestionList.subList(startNum, endNum); 

	    // data0 分页信息
	    JsonObjectBuilder data0Builder = Json.createObjectBuilder();
	    data0Builder.add("totalPages", totalPages);
	    data0Builder.add("totalItems", totalItems);
	    JsonObject data0 = data0Builder.build();


	    // 转换为 JSON
	    JsonArrayBuilder data1Builder = Json.createArrayBuilder();
	    for (ChoiceQuestion question : choiceQuestionList) {
	        JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
	        objectBuilder.add("id", question.getC_id());
	        objectBuilder.add("choiceA", question.getC_choiceA());
	        objectBuilder.add("choiceB", question.getC_choiceB());
	        objectBuilder.add("choiceC", question.getC_choiceC());
	        objectBuilder.add("choiceD", question.getC_choiceD());
	        objectBuilder.add("question", question.getC_question());
	        objectBuilder.add("answer", question.getC_answer());
	        data1Builder.add(objectBuilder);
	    }
	    JsonArray data1 = data1Builder.build();


	    // 创建最终的 JSON 对象
	    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
	    jsonBuilder.add("info", data0);
	    jsonBuilder.add("data", data1);
	    JsonObject json = jsonBuilder.build();

	    // 将 JSON 发送回客户端
	    try (PrintWriter out = response.getWriter()) {
	        out.print(json.toString());
	    }
	}
	

	// 获取多选题分页信息
	private void getMultiChoiceQuestionPages(HttpServletRequest request, HttpServletResponse response) throws IOException {
	    // 设置响应内容类型为 JSON
	    response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");

	    // 获取传入学科id
	    String subjectid = request.getParameter("subjectid");
		
	    // pageSize: 每页展示条数
	    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		// curPage: 当前页数
	    int curPage = Integer.parseInt(request.getParameter("curPage"));
	    ManagementQuestionIF tc = DaoFactory.getTeacherDaoInstance();
	    // 选择
	    List<MultiChoiceQuestion> choiceQuestionList = tc.findMultiChoiceQuestion(subjectid);
	    
	    // 总数据条目数
	    int totalItems = choiceQuestionList.size(); 
	    // 总页数
	    int totalPages = (int) Math.ceil((double) totalItems / pageSize); 
	    // 计算起始索引
	    int startNum = (curPage - 1) * pageSize;
	    // 计算结束索引
	    int endNum = Math.min(startNum + pageSize , totalItems); 
	    // 获取当前页的数据
	    choiceQuestionList = choiceQuestionList.subList(startNum, endNum); 

	    // data0 分页信息
	    JsonObjectBuilder data0Builder = Json.createObjectBuilder();
	    data0Builder.add("totalPages", totalPages);
	    data0Builder.add("totalItems", totalItems);
	    JsonObject data0 = data0Builder.build();


	    // 转换为 JSON
	    JsonArrayBuilder data1Builder = Json.createArrayBuilder();
	    for (MultiChoiceQuestion question : choiceQuestionList) {
	        JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
	        objectBuilder.add("id", question.getM_id());
	        objectBuilder.add("choiceA", question.getM_choiceA());
	        objectBuilder.add("choiceB", question.getM_choiceB());
	        objectBuilder.add("choiceC", question.getM_choiceC());
	        objectBuilder.add("choiceD", question.getM_choiceD());
	        objectBuilder.add("question", question.getM_question());
	        objectBuilder.add("answer", question.getM_answer());
	        data1Builder.add(objectBuilder);
	    }
	    JsonArray data1 = data1Builder.build();

	    // 创建最终的 JSON 对象
	    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
	    jsonBuilder.add("info", data0);
	    jsonBuilder.add("data", data1);
	    JsonObject json = jsonBuilder.build();

	    // 将 JSON 发送回客户端
	    try (PrintWriter out = response.getWriter()) {
	        out.print(json.toString());
	    }
	}

	// 获取判断题分页信息
	private void getJudgeQuestionPages(HttpServletRequest request, HttpServletResponse response) throws IOException {
	    // 设置响应内容类型为 JSON
	    response.setContentType("application/json");
	    response.setCharacterEncoding("UTF-8");

	    // 获取传入学科id
	    String subjectid = request.getParameter("subjectid");
		
	    // pageSize: 每页展示条数
	    int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		// curPage: 当前页数
	    int curPage = Integer.parseInt(request.getParameter("curPage"));
	    ManagementQuestionIF tc = DaoFactory.getTeacherDaoInstance();
	    // 选择
	    List<JudgeQuestion> judgeQuestionList = tc.findjudgeQuestion(subjectid);
	    
	    // 总数据条目数
	    int totalItems = judgeQuestionList.size(); 
	    // 总页数
	    int totalPages = (int) Math.ceil((double) totalItems / pageSize); 
	    // 计算起始索引
	    int startNum = (curPage - 1) * pageSize;
	    // 计算结束索引
	    int endNum = Math.min(startNum + pageSize , totalItems); 
	    // 获取当前页的数据
	    judgeQuestionList = judgeQuestionList.subList(startNum, endNum); 

	    // 分页信息
	    JsonObjectBuilder data0Builder = Json.createObjectBuilder();
	    data0Builder.add("totalPages", totalPages);
	    data0Builder.add("totalItems", totalItems);
	    JsonObject data0 = data0Builder.build();


	    // 转换为 JSON
	    JsonArrayBuilder data1Builder = Json.createArrayBuilder();
	    for (JudgeQuestion question : judgeQuestionList) {
	        JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
	        objectBuilder.add("id", question.getJ_id());
	        objectBuilder.add("question", question.getJ_question());
	        objectBuilder.add("answer", question.getJ_answer());
	        data1Builder.add(objectBuilder);
	    }
	    JsonArray data1 = data1Builder.build();


	    // 创建最终的 JSON 对象
	    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
	    jsonBuilder.add("info", data0);
	    jsonBuilder.add("data", data1);
	    JsonObject json = jsonBuilder.build();

	    // 将 JSON 发送回客户端
	    try (PrintWriter out = response.getWriter()) {
	        out.print(json.toString());
	    }
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

